package com.example.hetong_system.controller;

import com.example.hetong_system.model.Customer;
import com.example.hetong_system.model.dto.CustomerContractStatsDTO;
import com.example.hetong_system.repository.CustomerRepository;
import com.example.hetong_system.service.ContractService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/auth")
public class CustomerController {

    @Autowired
    private CustomerRepository customerRepository;

    // 顾客修改密码接口（保持原有方法不变）
    @PutMapping("/customer/change-password")
    public ResponseEntity<?> changeCustomerPassword(
            @RequestParam String name,
            @RequestParam String oldPassword,
            @RequestParam String newPassword) {

        System.out.println("收到顾客修改密码请求：" + name + ", " + oldPassword); // 调试日志

        return customerRepository.findByContactNameAndPassword(name, oldPassword)
                .map(customer -> {
                    customer.setPassword(newPassword);
                    customerRepository.save(customer);
                    return ResponseEntity.ok("密码修改成功");
                })
                .orElseGet(() -> ResponseEntity.badRequest().body("用户名或原密码错误"));
    }


    /**
     * 新增：获取顾客的合同统计数据
     */
    @Autowired
    private ContractService contractService;
    @GetMapping("/customer/{customerId}/contract-stats")
    public ResponseEntity<CustomerContractStatsDTO> getCustomerContractStats(
            @PathVariable Long customerId) {
        // 调用Service层查询统计数据
        CustomerContractStatsDTO stats = contractService.getCustomerContractStats(customerId);
        return ResponseEntity.ok(stats);
    }

//    // 新增：获取所有顾客列表的方法
//    @GetMapping("/customers")
//    public ResponseEntity<List<Customer>> getAllCustomers() {
//        List<Customer> customers = customerRepository.findAll();
//        return ResponseEntity.ok(customers);
//    }
//
//    // 新增：根据ID获取顾客的方法
//    @GetMapping("/customers/{id}")
//    public ResponseEntity<Customer> getCustomerById(@PathVariable Long id) {
//        Optional<Customer> customer = customerRepository.findById(id);
//        return customer.map(ResponseEntity::ok)
//                .orElse(ResponseEntity.notFound().build());
//    }

    // 新增：获取所有客户
    @GetMapping("/customers")
    public ResponseEntity<List<Customer>> getAllCustomers() {
        List<Customer> customers = customerRepository.findAll();
        return ResponseEntity.ok(customers);
    }

    // 新增：根据ID获取客户
    @GetMapping("/customers/{id}")
    public ResponseEntity<Customer> getCustomerById(@PathVariable Long id) {
        Optional<Customer> customer = customerRepository.findById(id);
        return customer.map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }
}